<?php
class File {
	/**
	* @var mixed Mysql connection
	*/
	var $mysqli = null;
	/**
	* @var array User credentials (id, email, type)
	*/
	var $user = null;
	/**
	* @var array Notifications
	*/
	var $notif = array();
	/**
	* @var string Area of concentration
	*/
	var $area = null;
	/**
	* @var string Image table
	*/
	var $imgtb = null;
	/**
	* @var string Document table
	*/
	var $doctb = null;
	
	/**
	* File constructor
	* Initializes file variables for intended request
	* 
	* @param string $area Area of concentration
	* @param resource $mysqli Current mysql connection
	* @param resource $user User credentials (id, email, type)
	*/
	function __construct($area, $mysqli, $user) {
		# Include all necessary classes
		require_once "class/setting.php";
		require_once "class/resource.php";
		require_once "class/location.php";
		require_once "class/microorganism.php";
		require_once "class/image.php";
		require_once "class/document.php";
		require_once "class/section.php";
		require_once "class/project.php";
		require_once "class/tool.php";
		
		$this->mysqli = $mysqli;
		$this->user = $user;
		$this->area = $area;
		
		switch($area) {
			# Microorganism
			case 'micro':
				$this->imgtb = 'MicroImgs';
				$this->doctb = 'MicroDocs';
			break;
			
			# Project
			case 'proj':
				$this->imgtb = 'ProjImgs';
				$this->doctb = 'ProjDocs';
			break;
			
			# Location
			case 'loc':
				$this->imgtb = 'LocImgs';
				$this->doctb = 'LocDocs';
			break;
			
			# Resource
			case 'rsrc':
				$this->imgtb = 'RsrcImgs';
				$this->doctb = 'RsrcDocs';
			break;
		}
	}
	
	/**
	* Append files
	* Append files associated to that area
	* 
	* @access public
	* @param array $files Files to be appended
	* @param string $id ID of area
	* @param string $categ Category
	* @param string $visib Visibility
	*/
	public function append($files, $id, $categ, $visib) {
		# Iterate through each file
		foreach($files['name'] as $i => $name) {
			# Get file extension
			$ext = strtolower(substr($name, strrpos($name, '.')));
			
			switch($ext) {
				# Image file
				case ".jpg":
				case ".jpeg":
				case ".gif":
					# Create new image entry
					$img = new Image($this->area, array('id'=>$id), $this->mysqli, $this->user);
					$imgID = $img->create(
						array('name'=>$name, 'type'=>$files['type'][$i],
						'size'=>$files['size'][$i], 'tmp_name'=>$files['tmp_name'][$i], 'error'=>0),
						null, null, null, null, null, null, null, null, $categ, $visib
					);
					
					# Successfully created image
					if($imgID!==false) {
						$ins = "INSERT INTO {$this->imgtb} VALUES ('{$id}', '{$imgID}', '0', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."')";
						
						# Associate image to area
						if(!$this->mysqli->query($ins)) {
							$this->notif[] = "ERROR: ins file img";
						}
					}
				break;
				
				# Document file
				case ".pdf":
					# Create new document entry
					$doc = new Document($this->area, array('id'=>$id), $this->mysqli, $this->user);
					$docID = $doc->create(
						array('name'=>$name, 'type'=>$files['type'][$i],
						'size'=>$files['size'][$i], 'tmp_name'=>$files['tmp_name'][$i], 'error'=>0),
						null, null, null, null, null, null, null, null, $categ, $visib
					);
					
					# Created document successfully
					if($docID!==false) {
						$ins = "INSERT INTO {$this->doctb} VALUES ('{$id}', '{$docID}', '0', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."')";
						
						# Associate document to area
						if(!$this->mysqli->query($ins)) {
							$this->notif[] = "ERROR: ins file doc";
						}
					}
				break;
			}
		}
	}
	
	/**
	* Upload file
	* Upload one image or document
	* 
	* @access public
	* @param array $file File to be uploaded
	*/
	public function uploadOne($file) {
		$error = "";
		$msg = "";
		
		# Switch error signal
		if(!empty($file['error'])) {
			switch($file['error']) {
				case '1':
					$error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
					break;
				case '2':
					$error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
					break;
				case '3':
					$error = 'The uploaded file was only partially uploaded';
					break;
				case '4':
					$error = 'No file was uploaded.';
					break;
				case '6':
					$error = 'Missing a temporary folder';
					break;
				case '7':
					$error = 'Failed to write file to disk';
					break;
				case '8':
					$error = 'File upload stopped by extension';
					break;
				case '999':
				default:
					$error = 'No error code avaiable';
			}
		}
		# Empty temporary filepath
		elseif(empty($file['tmp_name']) or $file['tmp_name'] == 'none') {
			$error = 'No file was uploaded..';
		}
		# Successfully uploaded
		else {
			# Temporary details of file
			$name = substr(Tool::generateID('img'), 8, 15).'-'.$file['name'];
			$dir = 'data/tmp';
			$path = $dir.'/'.$name;
			
			if(!is_dir($dir)) {
				if(!mkdir($dir, 0777, true)) {
					$error .= ' Directory of uploaded file';
				}
			}
			
			if(empty($error)) {
				# Move file to temporary path
				if(!move_uploaded_file($file['tmp_name'], $path)) {
					$error .= " Cannot move uploaded file";
				}
			
				# Display message
				$msg .= " File Name: " . $name . ", ";
				$msg .= " File Size: " . filesize($path);
				$msg .= " File Path: " . addslashes($path);
			}
		}
		
		# Print json details
		echo "{";
		echo				"error: '" . $error . "',\n";
		echo				"msg: '" . $msg . "',\n";
		echo				"name: '" . addslashes($name) . "',\n";
		echo				"path: '" . addslashes($path) . "'\n";
		echo "}";
	}
	
	/**
	* Upload files
	* Upload many images or documents
	* 
	* @access public
	* @param array $files Files to be uploaded
	*/
	public function uploadMany($files) {
		foreach($files['name'] as $i => $name) {
			$this->uploadOne(array('name'=>$name, 'tmp_name'=>$files['tmp_name'][$i], 'type'=>$files['type'][$i], 'size'=>$files['size'][$i], 'error'=>$files['error'][$i]));
		}
	}
	
	/**
	* Remove files
	* Remove files from the system
	* 
	* @access public
	* @param array $files Files to be removed
	*/
	public function remove($files) {
		# Many files
		if(is_array($files)) {
			foreach($files as $file) {
				unlink($file);
			}
		}
		# One file
		else {
			unlink($files);
		}
	}
}
?>